package com.newangels.util;

import jade.core.Profile;
import jade.core.ProfileImpl;
import jade.core.Runtime;
import jade.wrapper.ContainerController;
import jade.wrapper.StaleProxyException;

import java.util.logging.Logger;

import static jade.core.Profile.LOCALHOST_CONSTANT;

/**
 * 启动Agent
 *
 * @author: TangLiang
 * @date: 2020/5/12 10:53
 * @since: 1.0
 */
public class startAgent {
    private static Logger logger = Logger.getLogger(startAgent.class.getName());
    private static Runtime rt = Runtime.instance();
    private static Object[] obj = new Object[1];

    static {
        rt.setCloseVM(true);
    }

    public static void main(String[] args) throws RuntimeException {
        Profile p = new ProfileImpl(false);
        p.setParameter(LOCALHOST_CONSTANT, LOCALHOST_CONSTANT);
        p.setParameter(Profile.MAIN_PORT, "1099");
        p.setParameter(Profile.CONTAINER_NAME, args[0]);
        ContainerController cc = rt.createAgentContainer(p);
        try {
            if (" ".equals(args[2])) {
                (cc.createNewAgent(args[0], args[1], null)).start();
            } else {
                obj[0] = args[2];
                (cc.createNewAgent(args[0], args[1], obj)).start();
            }
        } catch (StaleProxyException e) {
            logger.warning(args[0] + "Agent start failed\n" + e.getMessage());
            e.printStackTrace();
            try {
                cc.kill();
            } catch (StaleProxyException e1) {
                logger.warning("Container kill failed\n" + e1.getMessage());
                e1.printStackTrace();
            }
            //抛出异常交给servlet
            throw new RuntimeException("Agent start failed");
        }
    }
}
